package com.woniuxy.shiro.Utils;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO(用一句话描述这个类的作用)
 * @Author 18452
 * @Date 2021/5/6 19:28
 */
@Configuration
public class ShiroConfig {
    //配置securityManager,传入自定义域
    @Bean
    public DefaultWebSecurityManager getSecurityManager(MyRealm myRealm) {
        //相当于之前的记载的配置文件
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(myRealm);
        defaultWebSecurityManager.setRealm(myRealm);
        return defaultWebSecurityManager;
    }

    //工厂对象,设置过滤器
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //配置JWTFilter
        Map<String, Filter> filterHashMap = new HashMap<>();
        filterHashMap.put("JWT", new JWTFilter());
        shiroFilterFactoryBean.setFilters(filterHashMap);

        //配置url请求过滤条件!
        //过滤 URL请求, 使用 anon 任何人都能访问
        /*
         *   url过滤 条件 简写
         *   anon  匿名  所有用户未登录时 都能访问的接口
         *   authc  需要登录认证后 才能访问
         */
        Map<String, String> map = new HashMap<>();
        map.put("/login", "anon");
        //所有请求都要经过JWT过滤器
        map.put("/**", "JWT");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }
}
